import datetime
import os
import time

from loguru import logger
from playwright.sync_api import sync_playwright
import traceback
import yz.youzan_common as youzan_common

def group_by_period(job_list):
    job_group = {}
    period_list = list(set(map(lambda x: x['period'], job_list)))
    for period in period_list:
        filter_list = list(filter(lambda x: x['period'] == period, job_list))
        job_group[period] = filter_list
    return job_group

def youzan_main(host):
    try:
        log_file = os.path.join(os.getcwd(), 'logs', f'{datetime.datetime.now().strftime("%Y-%m-%d")}-youzan.txt')
        if not os.path.exists(log_file):
            logger.add(log_file)
        with sync_playwright() as playwright:
            youzan_func = youzan_common.YouZan(playwright, host, 'mudi-key')
            all_job_list = youzan_func.get_store_account('yz', '资金流水,资金流水总数')
            logger.info(all_job_list)
            if len(all_job_list) == 0:
                logger.info('没有配置到微店的登录账号信息')
                return
            store_id_list = list(set(map(lambda x: x['storeId'], all_job_list)))
            for store_id in store_id_list:
                # 过滤出当前店铺所有任务
                store_job_list = list(filter(lambda x: x['storeId'] == store_id, all_job_list))
                youzan_func.login(store_job_list[0])
                # 店铺任务按照周期分组
                job_group = group_by_period(store_job_list)
                for period, job_list in job_group.items():
                    param_list = []
                    file_list = []
                    logger.info(f'开始下载周期【{period}】的账单...')
                    for item in job_list:
                        for i in range(3):
                            try:
                                if item['accountType'] == '资金流水':
                                    start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                    logger.info('开始下载资金流水...')
                                    bill_file = youzan_func.download_fund_flow(item, period)
                                    if bill_file is not None:
                                        file_list.append(bill_file)
                                        dir_path, file_name = os.path.split(bill_file)
                                        param_list.append({'orderType': '资金流水', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                    else:
                                        param_list.append({'orderType': '资金流水', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                if item['accountType'] == '资金流水总数':
                                    start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                    bill_count = youzan_func.get_fund_flow_count(period)
                                    param_list.append({'orderType': '资金流水总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                break
                            except:
                                param_list = []
                                file_list = []
                                logger.info(traceback.format_exc())
                                youzan_func.close()
                                youzan_func.login(store_job_list[0])
                    # 编码字符串
                    coding_param = youzan_func.encode_param(param_list)
                    # 上传文件
                    uri = "api/v1/yzFundFlow/yzFundFlowRPAImport/{}".format(store_job_list[0]['storeCode'])
                    youzan_func.upload_file(uri, coding_param, file_list)
                youzan_func.close()
    except:
        traceback.print_exc()


